// UI元素
const musicContainer = document.getElementById('music-container');
const playBtn = document.getElementById('play');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');

const audio = document.getElementById('audio');
const progress = document.getElementById('progress');
const progressContainer = document.getElementById('progress-container');
const title = document.getElementById('title');
const cover = document.getElementById('cover');

// 歌曲列表
const songs = ['ukulele', 'summer', 'littleidea'];
let songIndex = 0;

// 初始化加载歌曲
loadSong(songs[songIndex]);

// 播放/暂停控制
function playSong() {
    musicContainer.classList.add('play');
    playBtn.querySelector('i.fas').classList.remove('fa-play');
    playBtn.querySelector('i.fas').classList.add('fa-pause');
    audio.play();
}

function pauseSong() {
    musicContainer.classList.remove('play');
    playBtn.querySelector('i.fas').classList.remove('fa-pause'); 
    playBtn.querySelector('i.fas').classList.add('fa-play');
    audio.pause();
}
// 加载歌曲
function loadSong(song) {
    title.innerText = song;
    audio.src = `music/${song}.mp3`;
    cover.src = `images/${song}.jpg`;
}

playBtn.addEventListener('click', function() {
    const isPlaying = musicContainer.classList.contains('play');
    if (isPlaying) {
        pauseSong();
    }else {
        playSong();
    }
}
)

// 改变歌曲
prevBtn.addEventListener('click', prevSong);
nextBtn.addEventListener('click', nextSong);

// 切换歌曲
function prevSong() {
   songIndex--;
   if (songIndex < 0) {
        songIndex = songs.length - 1;
    }
    loadSong(songs[songIndex]);
    playSong();
   }

function nextSong() {
    songIndex ++;
    if (songIndex > songs.length - 1) {
        songIndex = 0;
    }
    loadSong(songs[songIndex]);
    playSong();
}

// 歌曲时间
audio.addEventListener('timeupdate', updateProgress);


// 进度条更新
function updateProgress(e) {
    const { duration, currentTime } = e.srcElement;
    const progressPercent = (currentTime / duration) * 100;
    progress.style.width = `${progressPercent}%`;
}

// 点击进度条跳转
function setProgress(e) {
    const width = this.clientWidth;
    const clickX = e.offsetX;
    const duration = audio.duration;
    audio.currentTime = (clickX / width) * duration;
} 
// 歌曲结束
audio.addEventListener('ended', nextSong);